package client

import (
	"github.com/golang/glog"
	"github.com/oikomi/FishChatServer2/protocol/rpc"
	"github.com/oikomi/FishChatServer2/server/hall/conf"
	sd "github.com/oikomi/FishChatServer2/service_discovery/etcd"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

type LogicRPCCli struct {
	conn *grpc.ClientConn
}

func NewLogicRPCCli() (logicRPCCli *LogicRPCCli, err error) {
	r := sd.NewResolver(conf.Conf.RPCClient.LogicClient.ServiceName)
	b := grpc.RoundRobin(r)
	conn, err := grpc.Dial(conf.Conf.RPCClient.LogicClient.EtcdAddr, grpc.WithInsecure(), grpc.WithBalancer(b))
	if err != nil {
		glog.Error(err)
		panic(err)
	}
	logicRPCCli = &LogicRPCCli{
		conn: conn,
	}
	return
}

func (logicRPCCli *LogicRPCCli) CreateTable(uid int64) (res *rpc.LGCreateTableRes, err error) {
	createTableReq := &rpc.LGCreateTableReq{
		UID: uid,
	}
	l := rpc.NewLogicRPCClient(logicRPCCli.conn)
	if res, err = l.CreateTable(context.Background(), createTableReq); err != nil {
		glog.Error(err)
	}
	return
}

func (logicRPCCli *LogicRPCCli) EnterTable(tableID uint32, uid int64) (res *rpc.LGEnterTableRes, err error) {
	enterTableReq := &rpc.LGEnterTableReq{
		TableID: tableID,
		UID:     uid,
	}
	l := rpc.NewLogicRPCClient(logicRPCCli.conn)
	if res, err = l.EnterTable(context.Background(), enterTableReq); err != nil {
		glog.Error(err)
	}
	return
}
